<template>
<div>
     <fou-dialog :title="'收款'" v-model:dialogValue="dialogValue" :width="'75%'">
      <template #content="">
    <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="日期" prop="create_time"><el-input v-model="form.create_time" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="員工" prop="username"><el-input v-model="form.username" disabled  /></el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="學校" prop="school"><el-input v-model="form.school_name" disabled  /></el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="學生" prop="student_id">
              <el-button v-show="form.student_name" >{{form.student_name}}</el-button>
              <el-button  @click="addStudentTable" type="primary" circle icon="Search"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="isHide">
          <el-form-item label="發票" prop="invoice_id">
              <el-button  @click="addInvoiceTable" type="primary" circle icon="Search"></el-button>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="付款方式" prop="payment">
                <el-select  v-model="form.payment"  size="default" >
                  <el-option v-for="item in payment_options" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>

         <el-col :span="24">
          <el-form-item label="備註" prop="remark">
            <el-col :span="22">
              <el-input type="textarea" v-model="form.remark" ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="Search" circle @click="addRemarks('1','remark')">
              </el-button>
            </el-col>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客戶須知" prop="notice">
            <el-col :span="22">
              <el-input type="textarea" v-model="form.notice" ></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="primary" icon="Search" circle @click="addRemarks('2','notice')">
              </el-button>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row>
          <div v-show="isFlash">
              <div v-if="joinData.course.length>0">
                  <div class="text-lg">課程</div>
                      <ProTable
                        :data="joinData.course"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.product.length>0">
                  <div class="text-lg">產品</div>
                      <ProTable
                        :data="joinData.product"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.products_group.length>0">
                  <div class="text-lg">產品組合</div>
                      <ProTable
                        :data="joinData.products_group"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div v-if="joinData.ticket.length>0">
                  <div class="text-lg">套票</div>
                      <ProTable
                        :data="joinData.ticket"
                        :column="column"
                        :elProps="elProps"
                        :page="[]"
                        :rowControl="[]"
                        :disabled="[]"
                        :controlWidth="[]"
                      >
                            <template #default="{propname,row,index}">
                              <div v-if="propname == 'actual'">
                                <el-input type="number" v-model="row[propname]" :min="1" @change="handlerInput(row[propname],index)" @input="inputSort(row,index)"></el-input>
                              </div>
                            </template>
                      </ProTable>
              </div>
              <div class="flex justify-end mt-[15px] pr-[100px]">付款總金額：{{form.money}}</div>
          </div>
          <el-form-item label="產品/產品組合"  v-show="!isFlash" >
                <div class="product">
                        <el-button @click="addCourseProductsList('product','producttype','productList')" color="#50BC58"
                          icon="ZoomIn">產品
                        </el-button>
                        <el-button @click="addCourseProductsList('productGroup','producttype','productGroupList')" color="#50BC58"
                          icon="ZoomIn">產品組合</el-button>
                </div>
                <div>
                  <CourseProductsDio ref="CourseProductsRef" @update="getCourseProducts"></CourseProductsDio>
                </div>
      
          </el-form-item>
    </el-form>
              <div v-show="!isFlash">
                <div  v-if="formData.joinData.productList && formData.joinData.productList.length>0" >
                    <div  class="mt-[20px] text-lg font-bold">產品</div>
                      <product  class="mt-[20px]"  :list="formData.joinData.productList"   :discountSelect="discountSelect"
                    @del_course="(v)=>{delcourse('productList',v)}"
                    @input="(v)=>{onProductInput('productList',v)}"
                    @select="(v)=>{onProductSelect('productList',v)}"
                    ></product>
                </div>
                <div v-if="formData.joinData.productGroupList && formData.joinData.productGroupList.length>0">
                  <div  class="mt-[20px]  text-lg font-bold">產品組合</div>
                      <productGroup class="mt-[20px]"  :list="formData.joinData.productGroupList"   :discountSelect="discountSelect"
                      @del_course="(v)=>{delcourse('productGroupList',v)}"
                      @input="(v)=>{onProductInput('productGroupList',v)}"
                      @select="(v)=>{onProductSelect('productGroupList',v)}"
                      > </productGroup>
                </div>
                        <div>發票總數：{{invoiceData.num}}</div>
                        <div>發票金額：{{invoiceData.amount}}</div>
                </div>

           <div class="flex justify-end mt-10 w-[100%]" >
            <el-button @click="dialogValue = false">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef,buttonType)" color="#081F42">確定</el-button>
           </div>
      </template>
     </fou-dialog>
     <notes ref="notesRef" @update="getNotes"></notes>
     <student ref="studentRef" @update="getStudent"></student>
     <invoice ref="invoiceRef" @update="getInvoice"></invoice>
</div>
</template>

<script setup>
import { ref ,reactive,watch,onMounted,computed } from 'vue' 
import { dayjs } from "element-plus";
import {payment,addProceeds,updateProceeds,discounts,fastcreate} from '@/http/index.js'
import {message} from '@/common/function.js'
import notes from './notes/notes.vue'
import student from './student/student.vue'
import invoice from './invoice/invoice.vue'
import {elProps,column} from './index'
import { add, subtract, } from 'high-precision-four-fundamental-rules'
import CourseProductsDio from '../../invoice/addEdit/CourseProducts.vue'
import product from './product/product.vue'
import productGroup from './product/productGroup.vue'

const handlerInput = (row,index)=>{
    form.money = 0
    if (joinData.course) {
       for (let i = 0; i < joinData.course.length; i++) {
        console.log(joinData.course[i]);
      joinData.course[i].debts = subtract(parseFloat(joinData.course[i].debt),parseFloat(joinData.course[i].actual),2)
      form.money =  add(parseFloat(joinData.course[i].actual), form.money, 2)
       }
    }
    if (joinData.product) {
       for (let i = 0; i < joinData.product.length; i++) {
      joinData.product[i].debts = subtract(parseFloat(joinData.product[i].debt),parseFloat(joinData.product[i].actual),2)
      form.money =  add(parseFloat(joinData.product[i].actual), form.money, 2)
       }
    }
    if (joinData.products_group) {
       for (let i = 0; i < joinData.products_group.length; i++) {
      console.log(joinData.product);
      joinData.products_group[i].debts = subtract(parseFloat(joinData.products_group[i].debt),parseFloat(joinData.products_group[i].actual),2)
      form.money =  add(parseFloat(joinData.products_group[i].actual), form.money, 2)
       }
    }
    if (joinData.ticket) {
       for (let i = 0; i < joinData.ticket.length; i++) {
      console.log(joinData.product);
      joinData.ticket[i].debts = subtract(parseFloat(joinData.ticket[i].debt),parseFloat(joinData.ticket[i].actual),2)
      form.money =  add(parseFloat(joinData.ticket[i].actual), form.money, 2)
       }
    }
}
const inputSort = (row,index)=>{
  console.log(row);
        if (row.actual > (parseFloat(row.total_prices) - parseFloat(row.grandtotal))) {
          message('付款金額已超出現時尚欠數額，請重新輸入！','error')
          row.actual = subtract(parseFloat(row.total_prices), parseFloat(row.grandtotal), 2)
          // form.money = subtract(form.money, 1, 2)
        } else if (row.actual < 0) {
          message('請輸入正確金額！','error')
          row.actual  = subtract(parseFloat(row.total_prices), parseFloat(row.grandtotal), 2)
        }
}

const invoiceData = computed(()=>{
          let num = 0,
          amount = 0;
          for (let key in formData.joinData) {
          num += formData.joinData[key] && formData.joinData[key].length
          if (formData.joinData[key].length > 0) {
            formData.joinData[key].forEach(v => {
              console.log(v);
              if (v.status != -1) amount += Number(v.total_prices);
            })
          }
        }
        return {
          num: num,
          amount: amount
        }
})

const notesRef = ref('')
const addRemarks = async (type,name)=>{
  await notesRef.value.TableData(type)
  notesRef.value.dialogValue = true
  notesRef.value.name = name
}

const joinData = reactive({
    course:[],
    product:[],
    products_group:[],
    ticket:[]
})
const dialogValue = ref(false)
const rules = reactive({
  student_id: [{ required: true, message: "請選擇學生", trigger: ["blur",'change'] }],
  invoice_id: [{ required: true, message: "請選擇發票", trigger: ["blur",'change'] }],
  payment: [{ required: true, message: "請選擇付款方式", trigger: ["blur",'change'] }],
});
const form = reactive({
    create_time:dayjs().format('YYYY-MM-DD HH:mm:ss'),
    username:localStorage.getItem('username'),
    school_name:localStorage.getItem('school_name'),
    school_id:localStorage.getItem('school_id'),
    student_name:'',
    invoice_id:'',
    student_id:'',
    money:0,
    payment:'',
    remark:'',
    notice:'',
    debt:''
});
const props = defineProps({
  echo:Object,
})
Object.assign(form,props.echo)
joinData.course = props.echo.course
joinData.product = props.echo.product
joinData.products_group = props.echo.products_group
joinData.ticket = props.echo.ticket
watch(()=>props.echo,(neaval)=>{
  Object.assign(form,neaval)
  console.log(form);
  console.log(neaval);
joinData.course = neaval.course
joinData.product = neaval.product
joinData.products_group = neaval.products_group
joinData.ticket = neaval.ticket
})
const studentRef = ref('')
const addStudentTable = async()=>{
  await studentRef.value.TableData()
  studentRef.value.studentDia = true
}
const invoiceRef = ref('')
const addInvoiceTable = async()=>{
    if (!form.student_id) {
        message('請添加學生信息','warning')
    }else{
  await invoiceRef.value.TableData(form.student_id)
  invoiceRef.value.dialogValue = true
    }
}

// 添加备注须知信息
const getNotes = (row,name)=>{
    if (name == 'remark') {
      form.remark = row.content
    }
    if (name == 'notice') {
      form.notice = row.content
    }
}
// 添加學生信息
const getStudent = (row)=>{
  form.student_name = row.name
  form.student_id = row.id
}

// 添加發票信息
const getInvoice = (row)=>{
  console.log(row);
    form.invoice_id = row.id
    form.debt = row.debt
    form.money = 0
    if (row.course && row.course.length>0) {
      row.course.map(e=>{
      e.number = row.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt = e.total_prices,e.debts = e.total_prices
      form.money =  add(parseFloat(e.total_prices), form.money, 2)
      } )
      joinData.course = row.course
    }
    if (row.product && row.product.length>0) {
      row.product.map(e=>{
      e.number = row.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt =  e.total_prices,e.debts = e.total_prices
      form.money =  add(parseFloat(e.total_prices), form.money, 2)} )
      joinData.product = row.product
    }
    if (row.products_group && row.products_group.length>0) {
      row.products_group.map(e=>{
        e.number = row.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt =  e.total_prices,e.debts = e.total_prices
      form.money =  add(parseFloat(e.total_prices), form.money, 2)} )
      joinData.products_group = row.products_group
    }
    if (row.ticket && row.ticket.length>0) {
      row.ticket.map(e=>{
        e.number = row.number, e.grandtotal = 0,e.actual=e.total_prices,e.debt =  e.total_prices,e.debts = e.total_prices
      form.money =  add(parseFloat(e.total_prices), form.money, 2)} )
      joinData.ticket = row.ticket
    }
}
//付款方式
const payment_options = ref([])
const paymentData = async()=>{
    const data = await payment()
    if (data.code == 200) {
        payment_options.value = data.data.data
    }
}
const ruleFormRef = ref('')
const emit = defineEmits(['update'])
const confirm = async (formEl,type) => {
  if (!formEl) return;
    formEl.validate(async (e)=>{
      if (e) {
        console.log(form.debt,form.money);
        let course = joinData.course.map(e=>({invoice_details_id:e.id,money:e.actual,debt:e.debts}))
        let product = joinData.product.map(e=>({invoice_details_id:e.id,money:e.actual,debt:e.debts}))
        let products_group = joinData.products_group.map(e=>({invoice_details_id:e.id,money:e.actual,debt:e.debts}))
        let ticket = joinData.ticket.map(e=>({invoice_details_id:e.id,money:e.actual,debt:e.debts}))
        form.data = [...course,...product,...products_group,...ticket]
        form.debt = subtract(parseFloat(form.debt), parseFloat(form.money), 2)
        console.log(form);
        if (type == 'add') {
            const data = await addProceeds(form)
            if (data.code == 200) {
              message('添加收款成功')
              emit('update')
              dialogValue.value = false
            }
        }
        if (type == 'edit') {
            const data = await updateProceeds(form)
              if (data.code == 200) {
              message('收款成功')
              emit('update')
              dialogValue.value = false
            }
        }
        if (type == 'quick') {
          console.log(formData);
             if (formData.joinData.productList.length ==0 && 
            formData.joinData.productGroupList.length ==0 ) {
          return message('請至少選擇產品|產品組合 之一','warning')
        }
        let product = formData.joinData.productList.map(e=>({
          id:e.id,
          name:e.name,
          type:'1',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        let productGroup = formData.joinData.productGroupList.map(e=>({
          id:e.id,
          name:e.name,
          type:'2',
          num:e.num,
          discount_id:e.discount_id,
          discount_price:e.discount_price,
          total_prices:e.total_prices,
          price:e.price
        }))
        form.data = [...product,...productGroup]
        form.money = invoiceData.value.amount
          console.log(form);
            const data = await fastcreate(form)
              if (data.code == 200) {
              message('快速收款成功')
              emit('update')
              dialogValue.value = false
            }
        }
        // dialogValue.value = false
      }
    })
};

const discountSelect = ref([])
const getDiscounts = async()=>{
  let obj = {limit:100}
  const data = await discounts(obj)
  if (data.code == 200) {
    discountSelect.value = data.data.data
  }
}
// 快速收款
const CourseProductsRef = ref('')
const addCourseProductsList = async(url,type_url,indexUrl)=>{
    CourseProductsRef.value.indexUrl = indexUrl //點擊哪一分類
    CourseProductsRef.value.TableDatatype(type_url)//類別
    await CourseProductsRef.value.TableData(url)//列表
    CourseProductsRef.value.CourseProductsDia = true
}
const formData = reactive({
          joinData: {
            productList: [], //產品
            productGroupList: [], //產品組合
          }
})
const getCourseProducts = (row,type,indexUrl)=>{
  console.log(indexUrl,formData.joinData[indexUrl]);
       let equation = row.filter(item => !formData.joinData[indexUrl].some(y => y.id === item.id))
       console.log(equation);
       equation.map(e=> e.pay_money = e.price)
       
       if (equation.length != 0 ) {
          formData.joinData[indexUrl] = [...formData.joinData[indexUrl],...equation]
       }else{
            message('重複選項不可選','warning')
       }
}
      //課程|產品|產品組合 輸入
     const onProductInput=(indexStr, data) =>{
        let item = formData.joinData[indexStr][data.index]
        console.log(item,data);
        let totalprice = null
        switch (data.key) {
            case 'num':
            totalprice = (data.val * item.price)
            break;
          case 'price':
            totalprice = (data.val * item.num)
            item.pay_money = item.price
            break;
          case 'discount':
            totalprice = (item.price * item.num)
            break;
          case 'pay_money':
            item.price = item.pay_money
        }
            if (item.discount && item.discount.indexOf('%') > -1) {
          item.total_prices = totalprice - (totalprice * (parseInt(item.discount) * 0.01))
        } else if (item.discount) {
          item.total_prices = totalprice - 0
        } else {
          item.total_prices = totalprice
        }
        // item.total_prices = subtract(item.total_prices, Number(item.discount_price || 0), 2)
        item.total_prices = item.total_prices-Number(item.discount_price)
        if (item.total_prices < 0) {
          item.total_prices = totalprice
          item.discount_price = 0
          item.discount = ''
          item.discount_id = ''
          message('折扣超出付款金額','warning')
        }
      }
      const delcourse = (indexStr,row)=>{
  let item = formData.joinData[indexStr]
  formData.joinData[indexStr]  = item.filter(item => item.id != row.id)
}
      //課程|產品|產品組合 折扣下拉選擇
     const onProductSelect=(indexStr, data)=> {
      console.log(indexStr, data);
        let item = formData.joinData[indexStr][data.index]
        console.log(item);
        let totalprice = item.num * item.price
        let diffVal = null
        let discount = null
        if (Boolean(data.item)) {
          item.discount = data.item.discount
          discount = data.item.discount
        } else {
          discount = 0
        }
        if (discount.toString().indexOf('%') > -1) {
          diffVal = (totalprice * (parseInt(discount) * 0.01))
        } else {
          item.discount = ''
          item.discount_id = ''
          diffVal = 0
           message('該折扣格式不正確不可用','warning')
        }
        // item.total_prices = subtract(totalprice, (diffVal + parseInt(item.discount_price ||
        //   0)), 2)
        item.total_prices = totalprice-diffVal-parseInt(item.discount_price)
        if (item.total_prices < 0) {
          item.total_prices = totalprice
          item.discount_price = 0
          item.discount = ''
          item.discount_id = ''
          message('折扣超出付款金額','warning')
        }
      }
onMounted(() => {
  getDiscounts()
})
const isHide = ref(false)
const isFlash = ref(true)
const buttonType = ref('')
defineExpose({
    dialogValue,paymentData,isHide,isFlash,buttonType
})
</script>

<style lang='less'  scoped>
.el-col{
  padding: 0 !important;
}
.product{
  .el-button{
    color: #fff;
  }
}
</style>